package com.elitel.frame.base.component.quartz;

import com.elitel.common.quartz.AdaptableJobFactory;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.quartz.JobBuilder.newJob;

/**
 * 创建任务调度，并执行
 * created by guoyanfei on 2018/3/21
 */
@Component("quartzScheduler")
public class QuartzScheduler {

    private static final Logger logger = LoggerFactory.getLogger(QuartzScheduler.class);

    @Autowired
    private Scheduler scheduler;

    private static String JOB_GROUP_NAME = "ELITEL_JOBGROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "ELITEL_TRIGGERGROUP_NAME";


    /**
     * 添加一个调度任务
     * created on 2018/03/21
     * @param jobname 任务名称
     * @param cls 调度任务类
     * @param time 调度时间
     * @author guoyanfei
     */
    public void addJob(String jobname,Class cls,String time){
        try{
            //定义一个trigger
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobname, TRIGGER_GROUP_NAME) //定义name/group
                    .startNow()//一旦加入scheduler，立即生效
                    .withSchedule(
                            CronScheduleBuilder.cronSchedule(time))
                    .build();
            //定义一个JobDetail
            JobDetail job = newJob(cls) //定义Job类为searchServiceQuartz类，这是真正的执行逻辑所在
                    .withIdentity(jobname, JOB_GROUP_NAME) //定义name/group
                    .usingJobData("serviceId",jobname) //定义属性
                    .build();

            //加入任务调度
            scheduler.scheduleJob(job,trigger);

            //立即执行该任务
            scheduler.triggerJob(job.getKey(),job.getJobDataMap());

        }catch (SchedulerException e){
            e.printStackTrace();
        }

    }

    public void addJob(String groupname, String jobname,Class cls,int time){
        logger.info("Trigger key======="+groupname+"--"+jobname);
        try{
            //定义一个trigger
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobname, groupname) //定义name/group
                    .startNow()//一旦加入scheduler，立即生效
                    .withSchedule(
                            SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(time)
                            .repeatForever())
                    .build();
            //定义一个JobDetail
            JobDetail job = newJob(cls) //定义Job类为searchServiceQuartz类，这是真正的执行逻辑所在
                    .withIdentity(jobname, groupname) //定义name/group
                    .usingJobData("serviceId",jobname) //定义属性
                    .build();

            //加入任务调度
            scheduler.scheduleJob(job,trigger);


        }catch (SchedulerException e){
            e.printStackTrace();
        }

    }

    /**
     * 按组删除调度任务组
     * @param groupName
     * @throws SchedulerException
     */
    public void deleteJobs(String groupName) throws SchedulerException {
        Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(groupName));
        if (jobKeys.isEmpty())
            return;
        List<JobKey> list = new ArrayList<JobKey>(jobKeys);
        scheduler.deleteJobs(list);
    }

    /***
     * show 通过groupname刷新任务时间
     * create by guoyanfei on 2018/12/22
     * @param groupName 分组名称
     */
    public void refreshJobTime(String groupName){
        try{
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(groupName));
            List<JobKey> list = new ArrayList<JobKey>(jobKeys);
            if(list != null && list.size() > 0){
                for (JobKey jobKey : list){
                    TriggerKey triggerKey = new TriggerKey(jobKey.getName(),groupName);
                    SimpleTrigger  oldtrigger = (SimpleTrigger)scheduler.getTrigger(triggerKey);
                    int time = (int)oldtrigger.getRepeatInterval()/1000;
                    logger.info("强制刷新时间========"+time);
                    TriggerBuilder tb = oldtrigger.getTriggerBuilder();
                    Trigger newtrigger = tb.startNow()
                            .withIdentity(jobKey.getName(),groupName)
                            .withSchedule(
                                    SimpleScheduleBuilder.simpleSchedule()
                                            .withIntervalInSeconds(time)
                                            .repeatForever()
                             ).build();
                    JobDetail job = scheduler.getJobDetail(jobKey);
                    scheduler.deleteJob(jobKey);
                    scheduler.scheduleJob(job,newtrigger);
                }
            }
        }catch (SchedulerException e){
            e.printStackTrace();
        }

    }

    /**
     * 刷新job任务
     * @param groupName
     * @param jobName
     * @throws SchedulerException
     */
    public void refreshJobTime(String groupName, String jobName) {
        logger.info("Trigger key======="+groupName+"--"+jobName);

        //删除任务
        JobKey jobKey = new JobKey(jobName,groupName);
        try {
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(groupName));
            List<JobKey> list = new ArrayList<JobKey>(jobKeys);
            TriggerKey triggerKey = new TriggerKey(jobKey.getName(),groupName);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (trigger == null )
                return;
            SimpleTrigger  oldtrigger = (SimpleTrigger)scheduler.getTrigger(triggerKey);
            int time = (int)oldtrigger.getRepeatInterval()/1000;
                logger.info("强制刷新时间========"+time);

            TriggerBuilder tb = oldtrigger.getTriggerBuilder();
            Trigger newtrigger = tb.startNow()
                    .withIdentity(jobKey.getName(),groupName)
                    .withSchedule(
                            SimpleScheduleBuilder.simpleSchedule()
                                    .withIntervalInSeconds(time)
                                    .repeatForever()
                    ).build();
            JobDetail job = scheduler.getJobDetail(jobKey);
            scheduler.deleteJob(jobKey);
            scheduler.scheduleJob(job,newtrigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }

    /**
     * show 修改一个任务时间
     * created on 2018/03/21
     * @param jobname 任务名称
     * @param time 调度时间
     */
    public void updateJobTime(String jobname,String time){
        try{
            TriggerKey triggerKey = new TriggerKey(jobname,TRIGGER_GROUP_NAME);
            CronTrigger  oldtrigger = (CronTrigger)scheduler.getTrigger(triggerKey);
            if(oldtrigger == null){
                return;
            }

            String oldTime = oldtrigger.getCronExpression();
            if(!oldTime.equalsIgnoreCase(time)){
                TriggerBuilder tb = oldtrigger.getTriggerBuilder();
                Trigger newtrigger = tb.withSchedule(
                        CronScheduleBuilder.cronSchedule(time)
                ).build();
                scheduler.rescheduleJob(triggerKey,newtrigger);
            }
        }catch (SchedulerException e){
            e.printStackTrace();
        }

    }

    /**
     * show 移除一个任务
     * created on 2018/03/21
     * @param jobname 任务名称
     * @author guoyanfei
     */
    public void removeJob(String jobname){
        try {
            //停止触发器
            TriggerKey triggerKey = new TriggerKey(jobname,TRIGGER_GROUP_NAME);
            scheduler.pauseTrigger(triggerKey);
            //移除触发器
            scheduler.unscheduleJob(triggerKey);
            //删除任务
            JobKey jobKey = new JobKey(jobname,JOB_GROUP_NAME);
            scheduler.deleteJob(jobKey);
        }catch (SchedulerException e){
            e.printStackTrace();
        }
    }

    public void removeJob(String groupName, String jobName){
        try {
            //停止触发器
            TriggerKey triggerKey = new TriggerKey(jobName,groupName);
            scheduler.pauseTrigger(triggerKey);
            //移除触发器
            scheduler.unscheduleJob(triggerKey);
            //删除任务
            JobKey jobKey = new JobKey(jobName,groupName);
            scheduler.deleteJob(jobKey);
        }catch (SchedulerException e){
            e.printStackTrace();
        }
    }

    /**
     * 启动所有调度任务
     * created by guoyanfei on 2018/03/21
     */
    public void startJobs(){
        try{
            scheduler.start();
        }catch (SchedulerException e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭所有调度任务
     * created by guoyanfei on 2018/03/21
     */
    public void shutdownJobs(){
        try {
            if(!scheduler.isShutdown()){
                scheduler.shutdown();
            }
        }catch (SchedulerException e){
            e.printStackTrace();
        }
    }





}
